<script setup>
import {
    Edit, Delete, Position, Upload
} from '@element-plus/icons-vue'
import {

} from '@/api/allApi.js'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getquoteservice, deletef3service } from '@/api/allApi.js'
import {
    addquoteservice, selectByStrForQuoteservice, getchanceandclientservice,
    getAllUserForClientComeAddservice, deletequoteservice, addquoteandproductionpsservice,
    updatequotecomeservice, updatequoteandproductionpsservice, loadquoteproductionsservice,
} from '@/api/client.js'
//控制添加分类弹窗
const dialogVisible = ref(false)
const lenddialogVisible = ref(false)
//分页条数据模型
//const pageNum = ref(1)//当前页
const total = ref(20)//总条数
//const pageSize = ref(3)//每页条数
//文章分类数据模型
const users = ref([])
const chanceandclient = ref([])
const productionps = ref([])
//用户搜索时选中的分类id
const chanceslist = async () => {
    let result = await getchanceandclientservice();
    chanceandclient.value = result.data;
    console.log(chanceandclient.value);
}
chanceslist();
const listuser = async () => {
    let result = await getAllUserForClientComeAddservice();
    users.value = result.data;
    console.log(result);
}
listuser();
//定义变量，控制标题
const title = ref('')
//与后端交互的json数据
const pathmodel = ref({
    id: null,
    chanceid: null,
    chancename: null,
    clientcompanyname: null,
    budget: null,
    phase: null,
    pet: null,
    allprices: null,
    quotename: null,
    type: null,
    taxrate: null,
    comment: null
})
const pathmodelproduction = ref({
    selectnumber: null
})
const sheets = ref([{}, {}])

const findmodel = ref({
    pageNum: 1,
    pageSize: 5,
    str: ''
})
const findmodelproductionps = ref({
    str: ''
})
const f3list = async () => {
    console.log(findmodel.value);
    let result = await getquoteservice(findmodel.value);
    console.log(result);
    total.value = result.data.total;
    sheets.value = result.data.items;
}
f3list();
const productionpslist = async () => {
    let result = await selectByStrForQuoteservice(findmodelproductionps.value.str);
    console.log(result.data);
    const newProductionps = result.data.map(production => {
        // 为每个元素添加新属性
        production.maxselect = production.number + production.selectnumber;
        return production;
    });

    productionps.value = newProductionps;
}
productionpslist()
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    findmodel.value.pageSize = size;
    f3list();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    findmodel.value.pageNum = num;
    f3list();
}
const cleardata = () => {
    findmodel.value.str = ''
}
const cleardata2 = () => {
    findmodelproductionps.value.str = ''
}
//表单校验
const rules = {
    chancename: [
        { required: true, message: '请选择机会', trigger: 'blur' },
    ],
    quotename: [
        { required: true, message: '请输入名称', trigger: 'blur' },
    ],
    type: [
        { required: true, message: '请选择类型', trigger: 'blur' },
    ],
    taxrate: [
        { required: true, message: '请输入税率', trigger: 'blur' },
    ],
    comment: [
        { required: true, message: '请输入备注', trigger: 'blur' },
    ],
    xx: [
        { required: false, message: '', trigger: 'blur' },
    ]
}
const add = () => {

    for (let key in pathmodel.value) {
        if (pathmodel.value.hasOwnProperty(key)) {
            pathmodel.value[key] = null;
        }
    }
    pathmodel.value.allprices = 0..toFixed(2)
    productionpslist()
    userdepartment.value = null
    dialogVisible.value = true;
    title.value = '添加报价信息'
}
const formref = ref(null); //表单校验
const addpath = async () => {
    console.log(pathmodel.value);
    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            console.log(pathmodel.value);
            let result = await addquoteservice(pathmodel.value);
            let result2 = await addquoteandproductionpsservice(productionps.value, result.data);
            if (result.code == 0 && result2.code == 0) {
                ElMessage.success("添加成功")
                dialogVisible.value = false;
                f3list();
            }
            else {
                ElMessage.error(result.message ? result.message : '添加失败')
            }
        }
    });
}
const updatepath = async () => {
    console.log(pathmodel.value);
    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {
            console.log(pathmodel.value);
            let result = await updatequotecomeservice(pathmodel.value);
            let result2 = await updatequoteandproductionpsservice(productionps.value, pathmodel.value.id)
            if (result.code == 0 && result2.code == 0) {
                ElMessage.success("修改成功")
                dialogVisible.value = false;
                f3list();
            }
            else {
                ElMessage.error(result.message ? result.message : '修改失败')
            }
        }
    });
}
//删除分类
const del = (row) => {
    ElMessageBox.confirm(
        '你确认删除该条信息吗？',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //用户点击了确认
            let result = await deletequoteservice(row.id)
            if (result.code == 0) {
                ElMessage.success('删除成功')
                f3list();
            }
            else {
                ElMessage.error(result.message?result.message:'删除失败')
            }
        })
        .catch(() => {
            //用户点击了取消
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
//展示编辑弹窗
const showDialog = async (row) => {
    title.value = '编辑报价信息';
    dialogVisible.value = true;
    //数据拷贝
    Object.keys(row).forEach((key) => {
        if (key != 'chance') pathmodel.value[key] = row[key];//!!!!!!!!!!!!!!!!!!!!关联的实体必须为空
    });
    pathmodel.value.clientcompanyname = row.chance.clientCompany.clientcompanyname
    pathmodel.value.budget = row.chance.budget
    pathmodel.value.phase = row.chance.phase
    pathmodel.value.chancename = row.chance.chancename
    pathmodel.value.pet = row.chance.clientCompany.pet

    //加载该报价单的选择的产品
    let result = await loadquoteproductionsservice(row.id);
    console.log(result.data);
    const newProductionps = result.data.map(production => {
        // 为每个元素添加新属性
        production.maxselect = production.number + production.selectnumber;
        return production;
    });

    productionps.value = newProductionps;
}
const userdepartment = ref(null)


const handleSelectNumberChange = (row) => {
    console.log(row.selectnumber);
    console.log(row);

    let cha = (row.allprice - (row.selectnumber * row.price).toFixed(2)).toFixed(2)
    pathmodel.value.allprices = (pathmodel.value.allprices - cha).toFixed(2)
    let cha2 = (row.allprice - (row.selectnumber * row.price).toFixed(2)).toFixed(2)

    row.allprice = (row.allprice - cha2).toFixed(2)
    console.log(row.allprice);
}
const handleChanceChange = (id) => {
    const cc = chanceandclient.value.find(chanceandclient => chanceandclient.chanceid === id) ?
        chanceandclient.value.find(chanceandclient => chanceandclient.chanceid === id) : null;
    if (cc != null) {
        pathmodel.value.chanceid = cc.chanceid
        pathmodel.value.clientcompanyname = cc.clientcompanyname
        pathmodel.value.phase = cc.phase
        pathmodel.value.budget = cc.budget
        pathmodel.value.pet = cc.pet
    }
    else {
        pathmodel.value.chanceid = null
        pathmodel.value.clientcompanyname = null
        pathmodel.value.phase = null
        pathmodel.value.budget = null
        pathmodel.value.pet = null
    }
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>报价列表</span>
                <div class="extra">
                    <el-button type="primary" @click="add">新增报价</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item label="查询条件：">
                <el-input v-model="findmodel.str" placeholder="请输入查询内容" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="f3list">搜索</el-button>
                <el-button @click="cleardata">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 文章列表 -->
        <el-table :data="sheets" style="width: 100%">
            <el-table-column label="序号" width="60" type="index"> </el-table-column>
            <el-table-column label="报价编号" prop="id"> </el-table-column>
            <el-table-column label="报价客户" prop="chance.clientCompany.clientcompanyname"> </el-table-column>
            <el-table-column label="编辑日期" prop="quotedate"> </el-table-column>
            <el-table-column label="项目名称" prop="chance.projectname"> </el-table-column>
            <el-table-column label="报价总额" prop="allprices"></el-table-column>
            <el-table-column label="备注" prop="comment"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="del(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="findmodel.pageNum" v-model:page-size="findmodel.pageSize"
            :page-sizes="[5, 10, 15, 25]" layout="jumper, total, sizes, prev, pager, next" background :total="total"
            @size-change="onSizeChange" @current-change="onCurrentChange"
            style="margin-top: 20px; justify-content: flex-end" />
    </el-card>
    <!-- 添加分类弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="60%">
        <el-form :model="pathmodel" ref="formref" :rules="rules" label-width="100px" style="padding-right: 30px">
            <div class="basic-info-border">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="机会名称" prop="chancename">
                            <el-select placeholder="请选择..." clearable style="width: 300px" @change="handleChanceChange"
                                v-model="pathmodel.chancename">
                                <el-option v-for="c in chanceandclient" :key="c.chanceid" :label="c.chancename"
                                    :value="c.chanceid">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机会编号" prop="chanceid">
                            <el-input v-model="pathmodel.chanceid" disabled style="width: 300px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户" prop="clientcompanyname">
                            <el-input v-model="pathmodel.clientcompanyname" disabled style="width: 300px"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="阶段" prop="phase">
                            <el-input v-model="pathmodel.phase" disabled style="width: 300px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="行业" prop="pet">
                            <el-input v-model="pathmodel.pet" disabled style="width: 300px"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="预算" prop="budget">
                            <el-input v-model="pathmodel.budget" disabled style="width: 300px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
            <div class="basic-info-border2">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="报价名称" prop="quotename">
                            <el-input v-model="pathmodel.quotename" style="width: 300px"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="报价类型" prop="type">
                            <el-select placeholder="请选择类型" clearable style="width: 300px" v-model="pathmodel.type">
                                <el-option v-for="c in ['绝对价格报价', '相对价格报价', '投标最低价格报价', '量价报价']" :key="c" :label="c"
                                    :value="c">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="总价" prop="allprices">
                            <el-input v-model="pathmodel.allprices" disabled style="width: 300px"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="税率" prop="taxrate">
                            <el-input v-model="pathmodel.taxrate" type="number" style="width: 300px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="comment">
                            <el-input type="textarea" :rows="4" v-model="pathmodel.comment"
                                style="width: 723px"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
            <div class="basic-info-border3">
                <!-- 搜索表单 -->
                <!-- <el-form inline style="margin-left: 12px;">
                    <el-form-item label="查询条件：">
                        <el-input v-model="findmodelproductionps.str" placeholder="请输入查询内容"
                            style="width: 300px"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="productionpslist">搜索</el-button>
                        <el-button @click="cleardata2">重置</el-button>
                    </el-form-item>
                </el-form> -->
                <el-table :data="productionps" style="width: 100%">
                    <el-table-column label="序号" width="60" type="index"> </el-table-column>
                    <el-table-column label="产品" prop="name"></el-table-column>
                    <el-table-column label="库存" prop="number"></el-table-column>
                    <el-table-column label="报价(单价)" prop="price"></el-table-column>
                    <el-table-column label="报价(总价)" prop="allprice"></el-table-column>
                    <el-table-column label="是否呆滞" prop="isdull" width="80"></el-table-column>
                    <el-table-column label="选择数量" width="170">
                        <template #default="{ row }">
                            <el-input-number v-model="row.selectnumber" :min="0" :max="row.maxselect"
                                @change="handleSelectNumberChange(row)" />
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty description="没有数据" />
                    </template>
                </el-table>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="title == '添加报价信息' ? addpath() : updatepath()"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>

</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.basic-info-border {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    right: -10px;
    position: relative;
    padding-top: 30px;
    /* 增加内边距，为标题留出更多空间 */
    margin-right: -10px;
    /* 调整外边距，使边框线不重合 */
}

.basic-info-border::before {
    content: "机会信息";
    position: absolute;
    top: -15px;
    /* 将标题移动到边框上方 */
    left: 10px;

    /* 根据需要调整左边距 */
    background-color: #409EFF;
    color: white;
    padding: 5px;
    border-radius: 3px;
    font-weight: bold;
}

.basic-info-border2 {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    right: -10px;
    position: relative;
    padding-top: 30px;
    /* 增加内边距，为标题留出更多空间 */
    margin-right: -10px;
    /* 调整外边距，使边框线不重合 */
}

.basic-info-border2::before {
    content: "报价信息";
    position: absolute;
    top: -15px;
    /* 将标题移动到边框上方 */
    left: 10px;

    /* 根据需要调整左边距 */
    background-color: #409EFF;
    color: white;
    padding: 5px;
    border-radius: 3px;
    font-weight: bold;
}

.basic-info-border3 {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    right: -10px;
    position: relative;
    padding-top: 30px;
    /* 增加内边距，为标题留出更多空间 */
    margin-right: -10px;
    /* 调整外边距，使边框线不重合 */
}

.basic-info-border3::before {
    content: "设备及零件选择";
    position: absolute;
    top: -15px;
    /* 将标题移动到边框上方 */
    left: 10px;

    /* 根据需要调整左边距 */
    background-color: #409EFF;
    color: white;
    padding: 5px;
    border-radius: 3px;
    font-weight: bold;
}
</style>